package com.example.xinyun.slice;


import cn.droidlover.xrecyclerview.XRecyclerView;
import com.example.xinyun.MyApplication;
import com.example.xinyun.ResourceTable;
import com.example.xinyun.domain.UrlContant;
import com.example.xinyun.db.TbTz;
import com.example.xinyun.db.db_User;
import com.example.xinyun.domain.DataBase;
import com.example.xinyun.domain.convert;
import com.example.xinyun.init.InitNews;
import com.example.xinyun.init.InitPsychological;
import com.example.xinyun.provider.TabPageSilderProvider;
import com.example.xinyun.provider.TzProvider;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yan.zrefreshview.ZRefreshView;
import com.zzrv5.mylibrary.ZZRCallBack;
import com.zzrv5.mylibrary.ZZRHttp;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;

import java.util.ArrayList;
import java.util.List;


public class HomeFraction extends AbilitySlice {
    TabList tabList;
    PageSlider pageSlider;
    ZRefreshView zRefreshView;
    TaskDispatcher uiTaskDispatcher;
    private ArrayList<Object>  data = new ArrayList<>();;
    private TzProvider provide;

    @Override
    public void onStart(Intent intent) {



        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_home_fraction);
        MyApplication.homeContext = getContext();
        tabList = (TabList) findComponentById(ResourceTable.Id_tab_list);
        tabList.removeAllComponents();
        pageSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider);
        //初始化Tablist
        String[] tabs = {"新闻", "测评", "论坛", "我的"};

        for (String i : tabs) {

            TabList.Tab tab = tabList.new Tab(this);
            tab.setText(i);
            tabList.addTab(tab);
        }
        //初始化PageSilder
        List<Integer> layoutFileIds = new ArrayList<>();
        layoutFileIds.add(ResourceTable.Layout_ability_main);
        layoutFileIds.add(ResourceTable.Layout_psychological);
        layoutFileIds.add(ResourceTable.Layout_forum);
        layoutFileIds.add(ResourceTable.Layout_mine);
        pageSlider.setProvider(new TabPageSilderProvider(layoutFileIds, this));

        //tabLsit点击事件
        tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
            @Override
            public void onSelected(TabList.Tab tab) {
                //获取点击的菜单索引
                int index = tab.getPosition();
                //设置pageSlider的索引
                pageSlider.setCurrentPage(index);
                if (index == 0) {
                    initNews(pageSlider);
                } else if (index == 1) {
                    initPsychological(pageSlider);
                } else if (index == 2) {
                    initData();
                    initFourm(pageSlider);
                } else if (index == 3) {
                    initMine(pageSlider);
                }
            }

            @Override
            public void onUnselected(TabList.Tab tab) {

            }

            @Override
            public void onReselected(TabList.Tab tab) {

            }
        });
        //设置默认选中的tab
        tabList.selectTabAt(3);
        pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {

            }

            @Override
            public void onPageSlideStateChanged(int i) {

            }

            @Override
            public void onPageChosen(int i) {
                //i表示当前pageSlider的索引
                if (tabList.getSelectedTabIndex() != i)
                    tabList.selectTabAt(i);
            }
        });
    }

    //对新闻界面的逻辑处理
    private void initNews(PageSlider pageSlider) {
        //获取上下文对象
        Context context = getContext();
        uiTaskDispatcher = getUITaskDispatcher();
        //new一个InitNews对象
        InitNews initNews = new InitNews();
        //通过ID找到listContainer组件
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_news_list);
        //加载listContainer
        initNews.Refresh(UrlContant.URL+"selectNews", context, HomeFraction.this, listContainer);
        //listContainer的点击事件
        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                //创建一个意图
                Intent intent1 = new Intent();
                //以键值对的形式将新闻链接进行传递
                intent1.setParam("url", initNews.getNewsList().get(i).getUrl());
                //页面跳转
                present(new webSlice(), intent1);
            }
        });
        //下拉刷新
        zRefreshView = (ZRefreshView) findComponentById(ResourceTable.Id_refresh);
        zRefreshView.setOnRefreshListener(new ZRefreshView.RefreshListener() {
            @Override
            public void onPullRefreshing() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        uiTaskDispatcher.asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                zRefreshView.setHeaderTx("正在刷新");
                                initNews.Refresh(UrlContant.URL+"selectNews", context, HomeFraction.this, listContainer);
                                zRefreshView.setHeaderTx("刷新完成.....");
                                zRefreshView.setShowDuration(10);
                                zRefreshView.finishRefreshing();
                            }
                        });
                    }
                }).start();
            }
        });
    }

    //心理测评页面进行逻辑处理
    private void initPsychological(PageSlider pageSlider) {
        if (MyApplication.username==null)
        {
            Intent intent=new Intent();
            //页面跳转
            present(new LoginSlice(),intent);
        }else {
            //获取上下文对象
            Context context = getContext();
            //new一个InitNews对象
            InitPsychological initPsychological = new InitPsychological();
            //通过ID找到listContainer组件
            ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_Psychological);
            //加载listContainer
            String url1 = UrlContant.URL+"selectPsychologicalAll";
            initPsychological.Refresh(url1, context, HomeFraction.this, listContainer);
            //listContainer的点击事件
            listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
                @Override
                public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                    //创建一个意图
                    Intent intent2 = new Intent();
                    //以键值对的形式将调查问卷进行传递
                    String url=initPsychological.getXinliLists().get(i).getSrc();
                    intent2.setParam("url", url);
                    //页面跳转
                    present(new webSlice(), intent2);
                    initPsychological.updata(UrlContant.URL+"updatePsychological", initPsychological.getXinliLists().get(i).toString(), context);
                }
            });

        }
    }

    //对论坛进行逻辑处理
    private void initFourm(PageSlider pageSlider) {

        if (MyApplication.username==null)
        {
            Intent intent=new Intent();
            //页面跳转
            present(new LoginSlice(),intent);
        }else {
            XRecyclerView listContainer = (XRecyclerView) findComponentById(ResourceTable.Id_xr);
            listContainer.setLoadingListener(new XRecyclerView.LoadingListener() {
                @Override
                public void onRefresh() {
                    data.clear();
                    initData();
                }

                @Override
                public void onLoadMore() {

                }
            });
            provide = new TzProvider(getAbility(), data);
            listContainer.setItemProvider(provide);
        }

    }

    private void initData() {
        String url = UrlContant.URL+"selecttz?user=";
        ZZRHttp.get(url, new ZZRCallBack.CallBackString() {

            @Override
            //http访问出错，此部分在主线程中工作,可以更新UI等操做。
            public void onFailure(int code, String errorMessage) {
                new ToastDialog(getAbility())
                        .setText("加载失败，请检查网络连接！")
                        .show();
            }

            @Override
            //http访问成功，此部分在主线程中工作，可以更新UI等操作。
            public void onResponse(String response) {
                String s=response;
                //将http请求返回的json字符串转换成一个dbPsychological类的对象
                List<TbTz> list = new Gson().fromJson(response, new TypeToken<List<TbTz>>() {
                }.getType());
                if (list != null) {
                    if (data.size() != 0) {
                        data.clear();
                    }
                    data.addAll(list);
                    provide.notifyDataChanged();
                }
            }
        });
    }

    //对个人主页的逻辑处理
    private void initMine(PageSlider pageSlider) {
        if (!DataBase.readUser("username").equals("")) {
            MyApplication.username = DataBase.readUser("username");
        }
        Image user_Image = (Image) findComponentById(ResourceTable.Id_user_image);
        Text user_Name = (Text) findComponentById(ResourceTable.Id_user_name);
        DirectionalLayout tiz = (DirectionalLayout) findComponentById(ResourceTable.Id_owntz);
        DirectionalLayout setting = (DirectionalLayout) findComponentById(ResourceTable.Id_setting);
        DirectionalLayout exit = (DirectionalLayout) findComponentById(ResourceTable.Id_exit);

        user_Image.setCornerRadius(30f);

        if (MyApplication.username.equals("")) {
            Intent intent4 = new Intent();
            present(new LoginSlice(), intent4);
        } else if (MyApplication.username != "" && MyApplication.user_Image != null) {
            user_Name.setText(MyApplication.username);
            user_Image.setPixelMap(convert.ByteToPixelMap(MyApplication.user_Image));
        } else if (!MyApplication.username.equals("") && MyApplication.user_Image == null) {
            ZZRHttp.postJson(UrlContant.URL+"selectUser", "{\"user\":\"" + MyApplication.username + "\"}", new ZZRCallBack.CallBackString() {
                @Override
                public void onFailure(int i, String s) {
                    new ToastDialog(getContext()).
                            setText("网络连接失败！")
                            .show();
                }

                @Override
                public void onResponse(String s) {
                    db_User db_user = new Gson().fromJson(s, db_User.class);
                    //boolean b=db_user.getData().getUserImage()==null;
                    if (db_user.getData().getUserImage() == null) {
                        user_Image.setPixelMap(ResourceTable.Media_userImage);
                        MyApplication.user_Image = convert.PixelMapToBytes(user_Image.getPixelMap());
                    } else {
                        MyApplication.user_Image = db_user.getData().getUserImage();
                        user_Image.setPixelMap(convert.ByteToPixelMap(db_user.getData().getUserImage()));
                    }
                    user_Name.setText(db_user.getData().getUser());
                }
            });
        }
        tiz.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder().withDeviceId("")
                        .withBundleName("com.xijing.xinyun")
                        .withAbilityName("com.example.xinyun.TzOwnAbility")
                        .build();

                intent.setOperation(operation);
                getAbility().startAbility(intent);
            }
        });
        setting.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent = new Intent();
                present(new SettingSlice(), intent);
            }
        });
        exit.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                user_Name.setText("登录/注册");
                MyApplication.username = null;
                MyApplication.user_Image = null;
                DataBase.writeUser("username", "");
            }
        });
        user_Name.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                boolean equals = user_Name.getText().equals("登录/注册");
                boolean b = MyApplication.username == null;
                if (user_Name.getText().equals("登录/注册") && MyApplication.username == null) {
                    Intent intent4 = new Intent();
                    present(new LoginSlice(), intent4);
                }
            }
        });
    }


    private long mTouchTime = 0;

    //回退拦截
    @Override
    protected void onBackPressed() {
        long mWaitTime = 2000;
        long currentTime = System.currentTimeMillis();
        if ((currentTime - mTouchTime) >= mWaitTime) {
            mTouchTime = currentTime;
            //"再按返回键退出应用！"
            new ToastDialog(this)
                    .setText("再按返回键退出应用")
                    .show();
        } else {
            //退出应用
            terminateAbility();
        }
    }
}
